const router = require('koa-router')()
const svgCaptcha = require('svg-captcha')
const md5 = require('md5')
const url = require('url')
let Users = require('../../models/Users')

let resData
router.use(async (ctx, next) => {
  let pathName = url.parse(ctx.request.url).pathname.substring(1)
  resData = {
    code: 0,
    message: '',
    data: {}
  }
  if (ctx.session.userInfo) {
    await next()
  } else {
    if(pathName === 'blog/captcha' || pathName === 'blog/login' || pathName === 'blog/api/sortNavList') {
      await next()
    } else {
      resData.code = 9999
      resData.message = '登录过期'
      ctx.body = resData
    }
  }
})
// 验证码
router.get('/captcha', async (ctx) => {
  let captcha = svgCaptcha.create({
    size: 4,
    fontSize: 50,
    width: 89,
    height: 33,
    background: '#cc9966'
  })
  // 保存生成的验证码
  ctx.session.captcha = captcha.text
  // 返回验证码
  ctx.response.type = 'image/svg+xml'
  ctx.body = captcha.data
})
// 登录
router.post('/login', async (ctx) => {
  let {userName, password, captcha} = ctx.request.body
  //判断验证码是否输入正确
  if (captcha.toLocaleLowerCase() === ctx.session.captcha.toLocaleLowerCase()) {
    //验证用户名和密码是否正确
    let userResult = await Users.find({
      userName,
      password
    }, {
      password: 0,
      create_time: 0
    }).then(result => {
      return result
    })
    if (userResult.length > 0) {
      resData.message = '登录成功'
      resData.data = userResult[0]
      ctx.session.userInfo = userResult[0]
      ctx.body = resData
      Users.findByIdAndUpdate(ctx.session.userInfo._id, {
        last_time: new Date()
      })
    } else {
      resData.code = 2
      resData.message = '用户名或者密码错误'
      ctx.body = resData
    }
  } else {
    resData.code = 1
    resData.message = '验证码错误'
    ctx.body = resData
  }
})
//退出
router.get('/loginOut', async (ctx) => {
  ctx.session.userInfo = null
  resData.code = 0
  resData.message = '退出成功'
  ctx.body = resData
})
//修改密码
router.post('/changePassword', async (ctx) => {
  let {password, newPassword, rNewPassword} = ctx.request.body
  let resultUser = await Users.findById(ctx.session.userInfo._id).then(res => {
    return res
  })
  if (resultUser.password !== password) {
    resData.code = 1
    resData.message = '原密码错误'
    return ctx.body = resData
  } else {
    await Users.findByIdAndUpdate(ctx.session.userInfo._id, {
      password: newPassword
    }).then(res => {
      resData.code = 0
      resData.message = '修改成功'
      ctx.body = resData
    })
  }
})

module.exports = router.routes()
